package pl.register.android.activities.students.logic;

import android.app.ProgressDialog;
import android.content.Context;
import android.util.Log;
import android.widget.Toast;
import pl.register.android.database.exception.NotFoundCourseException;
import pl.register.android.activities.students.ui.StudentsView;
import pl.register.android.course.Course;
import pl.register.android.database.DatabaseAdapter;
import pl.register.android.database.dao.CourseDao;
import pl.register.android.database.dao.ProgramDao;
import pl.register.android.database.dao.StudentsDao;
import pl.register.android.database.dao.YearDao;
import pl.register.android.preferences.ResotorePreferences;
import pl.register.android.program.Program;
import pl.register.android.student.Student;
import pl.register.android.year.Year;
import pl.register.android.year.YearType;
import roboguice.util.RoboAsyncTask;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class AsyncStudentsLoader extends RoboAsyncTask<Void> {
    private static final String TAG = AsyncStudentsLoader.class.getSimpleName();

    private CourseDao courseDao;

    private YearDao yearDao;

    private ProgramDao programDao;

    private StudentsDao studentsDao;

    private ProgressDialog progressDialog;

    private StudentsPresenter presenter;

    private StudentsView view;

    private Course courseToRestore;

    public AsyncStudentsLoader(Context context, StudentsView view, StudentsPresenter presenter, Course courseToRestore) {
        super(context);
        this.view = view;
        this.presenter = presenter;
        this.courseToRestore = courseToRestore;

        DatabaseAdapter dbAdapter = presenter.getDatabaseAdapter();
        courseDao = dbAdapter.getCourseDao();
        yearDao = dbAdapter.getStudentYearDao();
        programDao = dbAdapter.getProgramDao();
        studentsDao = dbAdapter.getStudentDao();

        progressDialog = new ProgressDialog(context);
        progressDialog.setCancelable(false);
        progressDialog.setIndeterminate(true);
        progressDialog.setMessage("Inicjalizacja kursantów. Proszę czekać...");
    }

    @Override
    protected void onPreExecute() {
        progressDialog.show();
    }

    @Override
    public Void call() throws Exception {
        Course course = courseDao.findCourseFor(courseToRestore.getStartYear(), courseToRestore.getEndYear());
        List<Year> studentsYear = findYearsWithProgramAndStudents(course);
        course.setYears(studentsYear);
        Map<YearType, Year> yearMap = createYearMap(studentsYear);
        presenter.initWith(course, yearMap);
        ResotorePreferences.saveCourse(context, course);
        return null;
    }

    private List<Year> findYearsWithProgramAndStudents(Course course) {
        List<Year> studentYears = yearDao.findYearsBy(course);
        for (Year studentYear : studentYears) {
            Program program = programDao.findProgramFor(studentYear);
            studentYear.setProgram(program);

            List<Student> students = studentsDao.findStudentsBy(studentYear, course);
            studentYear.setStudents(students);
        }
        return studentYears;
    }

    private Map<YearType, Year> createYearMap(List<Year> years) {
        Map<YearType, Year> yearMap = new HashMap<YearType, Year>();
        for (Year year : years) {
            yearMap.put(year.getType(), year);
        }
        return yearMap;
    }


    @Override
    protected void onSuccess(Void result) {
        YearType selectedYearType = ResotorePreferences.getYearType(context);
        presenter.populateViews(selectedYearType);
    }

    @Override
    protected void onFinally() {
        if (progressDialog.isShowing()) {
            progressDialog.dismiss();
        }
    }

    @Override
    protected void onException(Exception exception) {
        try {
            throw exception;
        } catch (NotFoundCourseException e) {
//           view.showToastNotFoundGroup();
        } catch (Exception e1) {
            Toast.makeText(getContext(), "Wystąpił nieoczekiwany problem podczas zczytywania danch.", Toast.LENGTH_SHORT).show();
            e1.printStackTrace();
        }
        Log.e(TAG, exception.getMessage(), exception);
    }

}